using System;
using System.Collections.Generic;
using System.Windows.Controls;
using StoryDesigner.Controls;

namespace StoryDesigner
{
	public class UiManager
	{
		private readonly List<StoryControlBase> _controls;
		private readonly Canvas _workingSurface;

		private static UiManager _instance;
		public static UiManager Instance
		{
			get
			{
				if (_instance == null)
					throw new TypeInitializationException("UiManager", null);
				return _instance;
			}
		}

		public static void Initialize(Canvas workingSurface)
		{
			_instance = new UiManager(workingSurface);
		}

		private UiManager(Canvas workingSurface)
		{
			_controls = new List<StoryControlBase>();
			_workingSurface = workingSurface;
		}

		public void AddElement(StoryControlBase ctrl)
		{
			ctrl.GotFocus += CtrlGotFocus;
			_controls.Add(ctrl);
			Canvas.SetZIndex(ctrl, _controls.Count);
			_workingSurface.Children.Add(ctrl);
		}

		void CtrlGotFocus(object sender, EventArgs e)
		{
			BringToFront(sender as StoryControlBase);
		}

		public void BringToFront(StoryControlBase ctrl)
		{
			if (ctrl == null)
				return;
			_controls.Remove(ctrl);
			int i = 0;
			_controls.ForEach(it => Canvas.SetZIndex(it, i++));
			_controls.Add(ctrl);
			Canvas.SetZIndex(ctrl, _controls.Count);
		}

		public void Remove(StoryControlBase ctrl)
		{
			_controls.Remove(ctrl);
			_workingSurface.Children.Remove(ctrl);
		}

		public void Clear()
		{
			_controls.Clear();
			_workingSurface.Children.Clear();
		}
	}
}